<?php 
declare(strict_types=1);

namespace App\Service;

use App\Exception\BusinessException;
use Hyperf\Di\Annotation\Inject;
use App\Constants\ErrorCode;
use App\Dao\PermissionDao;
use App\Dao\RoleDao;
use App\Dao\RolePermissionDao;
use App\Dao\RoleAdminDao;
use App\Dao\AdminLogDao;


class RbcService
 { 

    /**
     * @Inject 
     * @var PermissionDao
     */
    protected $dao;

    /**
     * @Inject 
     * @var RoleDao
     */
    protected $roledao;

    /**
     * @Inject 
     * @var RolePermissionDao
     */
    protected $peroledao;

    /**
     * @Inject 
     * @var RoleAdminDao
     */
    protected $adroledao;

    /**
     * @Inject 
     * @var AdminLogDao
     */
    protected $logdao;


    public function menu($user_id){
        return $this->dao->searchPerByWhereId($user_id);
    }

    public function permissionAdd($data)
    {
        $where[] = ['identity','=' ,$data['identity']];
        $info = $this->dao->searchByWhereFirst($where);
        if($info){
            throw new BusinessException(ErrorCode::ERR_BUESSUS,'权限标识已被占用');
        }
        $data['add_time'] = time();
        $obj = $this->dao->add($data);
        //添加管理员操作日记
        $this->logdao->addLog('添加了权限,信息为'.json_encode($data));
        return;
    }

    public function editGet($id)
    {
        $where[] = ['id','=' ,$id];
        $obj = $this->dao->searchByWhereFirst($where);
        if($obj){
            $info = $obj->toArray();
            return $info;
        }else{
            throw new BusinessException(ErrorCode::ERR_BUESSUS,'权限不存在');
        }

    }

    public function editPost($data)
    {
        $where1[] = ['id','=' ,$data['id']];
        $obj = $this->dao->searchByWhereFirst($where1);
        $ori = json_encode($obj->toArray());
        $where[] = ['identity','=' ,$data['identity']];
        $info = $this->dao->searchByWhereFirst($where);
        if($info && $info->id != $data['id']){
            throw new BusinessException(ErrorCode::ERR_BUESSUS,'权限标识已被占用');
        }
        $data['update_time'] = time();
        $this->dao->update(['id'=>$data['id']],$data);
        $this->logdao->addLog('编辑了权限,信息由原值'.$ori.'修改成'.json_encode($data));
        return;
    }

    public function permissionDel($id)
    {
        $ids = [$id];
        $all = [$id];
        while ($ids = $this->dao->searchIdByIn($ids)) {
            $all = array_merge($all,$ids);
        }
        //日志用的原始值
        $arr = $this->dao->searchIdByIn($all);
        $ori = json_encode($arr);
        $this->logdao->addLog('删除了权限,信息为'.$ori);
        $this->dao->delDataByIn($all);
        return;
        
    }

    public function roleList($page,$pageSize)
    {
        $where = [];
        $data = $this->roledao->searchByWherePage($pageSize);
        $count = $this->roledao->countByWhere();
        return ['data'=>$data,'count'=>$count];

    }

   
    public function roleAll($user_id)
    {
        $where = [];
        if (!in_array($user_id, config('web.super'))) {
            $where[] = ['admin_id','=' ,$user_id];
        }
        $data = $this->roledao->allRoleByWhere($where);
        return $data;

    }


    
    public function roleAdd($data)
    {
        $where[] = ['name','=' ,$data['name']];
        $info = $this->roledao->searchByWhereFirst($where);
        if($info){
            throw new BusinessException(ErrorCode::ERR_BUESSUS,'角色名已被占用');
        }
        $data['add_time'] = time();
        $obj = $this->roledao->add($data);
       
        if ($obj) {
            //添加管理员操作日记
            $this->logdao->addLog('添加了角色,信息为'.json_encode($data));
            return $obj->id;
            
        } else {
            throw new BusinessException(ErrorCode::ERR_BUESSUS,'网络繁忙,请重试');  
             
        }

    }

    public function roleGet($id)
    {
        $where[] = ['id','=' ,$id];
        $obj = $this->roledao->searchByWhereFirst($where);
        if($obj){
            $info = $obj->toArray();
            return $info;
        }else{
            throw new BusinessException(ErrorCode::ERR_BUESSUS,'角色不存在');  
        }

    }

   
    public function rolePost($data)
    {
        $where1[] = ['id','=' ,$data['id']];
        $obj = $this->roledao->searchByWhereFirst($where1);
        $ori = json_encode($obj->toArray());
        $where[] = ['name','=' ,$data['name']];
        $info = $this->roledao->searchByWhereFirst($where);
        if($info && $info->id != $data['id']){
            throw new BusinessException(ErrorCode::ERR_BUESSUS,'角色名已被占用');
        }
        $data['update_time'] = time();
        $this->roledao->update(['id'=>$data['id']],$data);   
        //添加管理员操作日记
        $this->logdao->addLog('编辑了角色,信息由原值'.$ori.'修改成'.json_encode($data));
        return;

        
    }

    
    public function rolePermisionGet($role_id)
    {
        return $this->roledao->rolePermidByRoleid($role_id);
    }

    public function rolePermisionPost($data)
    {
        $role_id = $data['role_id'];
        $permission_id = $data['permission_id'];
        //先和之前的权限比较，看看权限有没有变化，有变化就通知前端
        //取出之前的权限
        $old_permission = $this->roledao->rolePermidByRoleid($role_id);
        sort($old_permission, SORT_NUMERIC);
        $old_permission = implode(',', $old_permission);
        $curren_permission = explode(',', $permission_id);
        sort($curren_permission, SORT_NUMERIC);
        $curren_permission = implode(',', $curren_permission);
        /*if ($old_permission != $curren_permission) {
            $user_all = static::manageIdByRole($role_id);
            foreach ($user_all as $v) {
                cache('update_permission' . $v['manage_id'], 1, 600);
            }
        }*/
        //删除角色的所有权限
        $this->peroledao->delete([$role_id]);
        //添加角色的权限
        if (!empty($permission_id)) {
            $permission_ids = explode(',', $permission_id);
            $map = [];
            foreach ($permission_ids as $k => $v) {
                $temp = [];
                $temp['permission_id'] = $v;
                $temp['role_id'] = $role_id;
                $map[] = $temp;
            }
            $this->peroledao->insert($map);
        } else {
            throw new BusinessException(ErrorCode::ERR_BUESSUS,'请选择权限');
        }
        //添加管理员操作日记
        $this->logdao->addLog('编辑的角色的权限,信息由原值'.json_encode(compact('old_permission','role_id')).'修改成'.json_encode(compact('curren_permission','role_id')));
        return;

        
        
    }
 
    public function roleDel($id)
    {
        $where[] = ['id','=' ,$id];
        $obj = $this->roledao->searchByWhereFirst($where);
        if(!$obj){
            throw new BusinessException(ErrorCode::ERR_BUESSUS,'没有该角色');
        }
        $where2[] = ['role_id','=' ,$id];
        $count = $this->adroledao->countByWhere($where2);
        if($count > 0){
            throw new BusinessException(ErrorCode::ERR_BUESSUS,'该角色绑定了用户');
        }

        //找出删除前的角色权限
        $where1[] = ['role_id','=' ,$id];
        $permission_id = $this->peroledao->peridByRoleid($where1);
        $this->peroledao->delete([$id]);
        $this->roledao->delDataByIn([$id]);
        //添加管理员操作日记
        $arr = $obj->toArray();
        $arr['permission_id'] = $permission_id;
        $this->logdao->addLog('删除了角色,内容为'.json_encode($arr));
        return;

    }

    

    

 }